#include <fstream>
#include <string>
#include <iterator>//迭代器
#include <iostream>
#include <curl/curl.h>
#include <sstream>//字符串流
#include <jsoncpp/json/json.h>
using namespace std;

//处理接受来自服务器的数据
size_t writecallback(void * contents, size_t size, size_t number, void* user_p)
{
    //将服务器的数据写入到用户空间
    ((std::stringstream *)user_p)->write((char *)contents, size*number);

//cout << (char *)contents <<endl;

    return size*number;
}



int main(int argc, char * argv[])
{

    cout <<"argc is" << argc << "\n" << endl;
    std::string filepatch(argv[1]);
    std::string question(argv[2]);



    std::ifstream recordFile(filepatch);
    if(!recordFile)
    {
        cout << "can't open recordFile" << endl;

        return 1;
    }
    //起始迭代器，结束标志迭代器，读取到文件结束符时结束，istreambuf_iterator不会跳过空白字符
    //入口参数加括号，默认是函数的构造，而不是声明
    std::string content((std::istreambuf_iterator<char>(recordFile)), (std::istreambuf_iterator<char>()));



 //   cout << content << endl;
   std::string prompt = content + "  " + question;//文件内容 + 问AI的问题 
    //recordFile.read();


    //打印出来读到的
 //   cout << content << endl;


    //关闭文件
    recordFile.close();


    //调用CURL使用HTTP库
    CURL *curl = curl_easy_init();
    if(!curl)
    {
        cout << "curl error\n" << endl;
    }

    Json::Value request_body;
    Json::Value system_mesage;
    Json::Value user_mesage;

    system_mesage["role"] ="system";
    system_mesage["content"] ="you are a helpful assistant.";
    user_mesage["role"] ="user";
    user_mesage["content"] = prompt;

    Json::Value messages(Json::arrayValue);
    messages.append(system_mesage);
    messages.append(user_mesage);


    request_body["model"] = "deepseek-chat";
    request_body["stream"] = false;
    request_body["messages"] = messages;


    Json::FastWriter writer;
    std::string post_data = writer.write(request_body);//转换成字符串



//-----------------------------请求数据
    //目标地址
    const std::string url ="https://api.deepseek.com/chat/completions" ;
    //内容的格式
    const std::string type = "Content-Type:application/json";

    const std::string Authorization = "Authorization: Bearer sk-e8dc46b5fb0c46ac8639b2d7689074c8" ;
    //请求体变量用于包含上俩内容
    struct curl_slist * hearders = nullptr;
    //填充格式
    hearders = curl_slist_append(hearders, type.c_str());//c_str把字符串对象转换成字符数组
    hearders = curl_slist_append(hearders, Authorization.c_str());
    //指定目标地址
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    //指定头
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hearders);
    //添加内容实体，添加数据段
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data.c_str());//传递字符串


//------------------------------处理响应数据
    //处理服务器的响应数据
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writecallback);
    //创建用户空间
    std::stringstream response_stream;//服务区的数据存储在这里
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_stream);







//发送请求
    CURLcode res = curl_easy_perform(curl);
    if(res != CURLE_OK)
    {
        cout << "curl run error\n" << endl;
        curl_slist_free_all(hearders);
        curl_easy_cleanup(curl);//释放所有的空间
         return 1;
    }

    
//    cout << "response_stream" << response_stream.str() << endl;


//解析response_stream为response_json
    Json::Value response_json;
    Json::CharReaderBuilder reader;
    std::string errs;
    if(!Json::parseFromStream(reader, response_stream, &response_json, &errs))
    {

        
        std::cerr << "parseFromStream error\n" << errs <<  endl;
            curl_easy_cleanup(curl);
            return 1;
    }
    if(response_json.isMember("error"))
    {



      std::cerr << "response_json error\n" << response_json["error"]["message"].asString() << endl;
            curl_easy_cleanup(curl);
            return 1;
    }
    if(response_json.isMember("choices") && !response_json["choices"].empty())
    {
        // cout << "123\n" << endl;
        Json::Value response_message = response_json["choices"][0]["message"];
        cout << "Role" << response_message["role"].asString() << endl;
        cout << "Content" << response_message["content"].asString()<<endl;       



        //写文件
        std::ofstream reportFile("report.txt");
        if(reportFile.is_open())//打不开就创建
        {

            reportFile << response_message["content"].asString();
            reportFile.close();
        }
        else
        {

            std::cerr << "can't open report.txt" << endl;
        }
    }
    else{





            std::cerr << "response_json format error\n"  << endl;
             curl_easy_cleanup(curl);
            return 1;
    }


    curl_slist_free_all(hearders);
    curl_easy_cleanup(curl);


    return 0;

}


//g++ deepseek_AA.cpp -o deeepseek -std=c++11 -lcurl -ljsoncpp

